// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @include      *.bilibili.com/video/*
// @include      *.bilibili.com/anime/*
// @include      *.bilibili.com/bangumi/play/*
// @require      http://localhost:3234/p-admin/dist/dist/gif.js
// @grant        none
// ==/UserScript==

(function () {
  "use strict";
  window.startGif = (customConfig) => {
    const videoEle = document.getElementsByTagName("video")[0];

    const config = {
      workers: 4,
      width: videoEle.videoWidth,
      height: videoEle.videoHeight,
      quality: 1,
    };

    const gif = new GIF({ ...config, ...customConfig });

    console.log(videoEle.videoWidth, videoEle.videoHeight);

    let startTime,
      sampleInterval = 100,
      timer;

    gif.on("start", () => {
      startTime = Date.now();
    });

    gif.on("progress", (p) => {
      console.log(`rendering: ${Math.round(p * 100)}%`);
    });

    gif.on("finished", (blob) => {
      console.log(URL.createObjectURL(blob));
      window.open(URL.createObjectURL(blob));
      gif.abort();
    });

    const capture = () => {
      gif.addFrame(videoEle, { copy: true, delay: sampleInterval });
    };

    videoEle.addEventListener("play", () => {
      clearInterval(timer);
      timer = setInterval(() => {
        capture();
      }, sampleInterval);
    });

    videoEle.addEventListener("pause", () => {
      clearInterval(timer);
      gif.render();
    });

    videoEle.addEventListener("ended", () => {
      clearInterval(timer);
      gif.render();
    });

    console.log("You can play video for start ");
    console.log("You can pause video for stop ");
  };
})();
